from rest_framework.permissions import BasePermission

from system.models import Resource


class Permission(BasePermission):
    """权限"""

    methods = {'GET': 0, 'POST': 1}

    def has_permission(self, request, view):
        """rbac 核型处理"""

        if not bool(request.user and request.user.is_authenticated):
            return False
        # 验证 用户角色权限 目前控制才菜单级别
        method = request.method
        path = request.path

        if method not in self.methods:
            return False

        # 权限优化
        queryset = Resource.objects.filter(
            method=self.methods[method],
            url=path,
            role_resource__role__user_role__user=request.user
        )
        if not queryset.exists():
            return False
        return True

    def has_object_permission(self, request, view, obj):
        """实例级别权限"""
        return True
